package com.fruit.listener;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.fruit.constants.OrderConstant;
import com.fruit.pojo.order.DSHOrder;
import com.fruit.service.order.DelayHandel;
import com.fruit.service.order.OrderHandel;
import com.fruit.service.redis.JedisUtil;
import com.fruit.service.order.DelayHandel.OnDelayedListener;
import com.fruit.util.CommonUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service  
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {  
      
  
    @Autowired
    private DelayHandel delayService;  
    
    @Autowired
    private OrderHandel orderHandel;
    
    @Autowired
    private JedisUtil jedisService;
    
    
    protected Logger logger = LoggerFactory.getLogger(StartupListener.class);
    
    public final static  ExecutorService OrderThreadPool = Executors.newFixedThreadPool(9);  
      
    @Override  
    public void onApplicationEvent(ContextRefreshedEvent evt) {  
        if (evt.getApplicationContext().getParent() == null) {
        	delayService.start(new OnDelayedListener() {
    			
    			@Override
    			public void onDelayedArrived(final DSHOrder order) {
    				
    				OrderThreadPool.execute(new Runnable(){
    					@Override
    					public void run() {
    						//处理订单
    						String tradeId = CommonUtil.getUUID();
    						log.info("[{}]-【取消订单】-【开始】-【订单号：{}】",tradeId,order.getOrderId());
    						if(order.getOrderId() != 0){
    							orderHandel.autoCancelOrder(tradeId, order, 3);
    						}
    						log.info("[{}]-【取消订单】-【结束】",tradeId);
    					}
    				});
    				
    			}
    		});
            
            //查找需要入队的订单  
            OrderThreadPool.execute(new Runnable(){  
                @Override  
                public void run() {
                	String tradeId = CommonUtil.getUUID();
                	log.info("[{}]-【从缓存读取取消订单】-【开始】",tradeId);
                    //扫描redis，找到所有可能的orderId  
                    Map<String, String> keys = jedisService.hgetAll(OrderConstant.ORDER_AUTO_CANCEL);
                    if(keys == null || keys.size() <= 0){  
                        return;  
                    }  
                    //写到DelayQueue  
                    for(String key : keys.keySet()){  
                    	
                        String value = keys.get(key);
                        log.info("[{}]-【从缓存读取取消订单】-【KEY：{}】-【VALUE：{}】",tradeId,key,value);
                        if(StringUtils.isNotEmpty(value)){
                        	DSHOrder dshOrder = new DSHOrder(Long.parseLong(key), Long.parseLong(value));
                            delayService.add(dshOrder);      
                        }  
                    }
                    log.info("[{}]-【从缓存读取取消订单】-【结束】",tradeId);
                }  
            }); 
        }  
        
        
        
    }  
}  
